﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace SQLTask2
{
    public partial class CountriesForm : Form
    {
        private MySqlConnection pConn;
        private MySqlDataAdapter da = null;
        private DataTable ds = null;
        private string[] queries = {//Fill main grid
                                    @"SELECT Country_ID AS `ID`,
                                             Name AS `Название`
                                     FROM countries",
                                    //Fill countries combobox
                                    @"SELECT Country_ID, Name FROM countries;"
                                   };


        public CountriesForm(MySqlConnection conn)
        {
            InitializeComponent();
            pConn = conn;
            ds = new DataTable();
        }

        private void UpdateMainTable()
        {
            try
            {
                ds.Clear();
                da.Fill(ds);
                dataGridView1.Refresh();
            }
            catch (MySqlException sqlExc)
            {
                MessageBox.Show(sqlExc.Message);
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            string query = @"INSERT INTO countries (Name) VALUES ('" + textBox1.Text + "');";
            MySqlCommand cmd = new MySqlCommand(query, pConn);
            try
            {
                cmd.ExecuteNonQuery();
                UpdateMainTable();
            }
            catch (MySqlException sqlExc)
            {
                MessageBox.Show(sqlExc.Message);
            }
        }

        private void CountriesForm_Load(object sender, EventArgs e)
        {
            try
            {
                da = new MySqlDataAdapter(queries[0], pConn);
                dataGridView1.DataSource = ds;
                UpdateMainTable();
            }
            catch (MySqlException sqlExc)
            {
                MessageBox.Show(sqlExc.Message);
            }
        }
    }
}
